package com.l.struct;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;

import com.l.statements.Comment;
import com.l.statements.Decrement;
import com.l.statements.Division;
import com.l.statements.Goto;
import com.l.statements.If;
import com.l.statements.Increment;
import com.l.statements.Init;
import com.l.statements.Multiplication;
import com.l.statements.Subtraction;
import com.l.statements.Sum;

public class Factory {

	private static HashMap<String, Statement> products = new HashMap<String, Statement>();
	private static ArrayList<Class<?>> shelf = new ArrayList<Class<?>>();

	static {
		shelf.add(Comment.class);
		shelf.add(Decrement.class);
		shelf.add(Division.class);
		shelf.add(Goto.class);
		shelf.add(If.class);
		shelf.add(Increment.class);
		shelf.add(Init.class);
		shelf.add(Multiplication.class);
		shelf.add(Subtraction.class);
		shelf.add(Sum.class);

		for (int i = 0; i < shelf.size(); i++) {
			Class<?> statement = shelf.get(i);
			Statement instance = (Statement) getInstance(statement);
//			products.put(instance.getStatementPattern(), instance);
		}

	}

	private static <T> T getInstance(Class<T> statement) {

		try {
			return (T) statement.newInstance();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	public static <T extends Statement> T getStatement(String command) {
		Set<String> keySet = products.keySet();
		for (String pattern : keySet) {
			if (command.matches(pattern)) {
				return (T) products.get(pattern);
			}
		}
		// it must be unreachable, otherwise, verifiy if all statements was put on shelf
		return null;
	}
}
